from PySide6.QtGui import QFont, Qt, QIntValidator, QValidator
from qfluentwidgets import Slider, LineEdit
from PySide6.QtWidgets import QFrame, QLabel, QLineEdit, QHBoxLayout

from components import Text15Label


class SliderFrame(QFrame):
    def __init__(self, parent=None, max=100):
        super().__init__(parent)
        self._font = QFont('微软雅黑', 10)

        self.hBox = QHBoxLayout(self)
        self.hBox.setContentsMargins(0, 0, 0, 0)
        # self.hBox.setSpacing(10)
        self.hBox.setAlignment(Qt.AlignmentFlag.AlignLeft)

        self.label = Text15Label(self)
        self.label.setFixedSize(100, 30)
        self.label.setAlignment(Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter)

        self.slider = Slider(Qt.Orientation.Horizontal, self)
        self.slider.setTracking(True)
        self.slider.setFixedWidth(300)
        self.slider.setSingleStep(1)

        self.lineEdit = LineEdit(self)
        self.lineEdit.setFixedSize(50, 30)
        self.lineEdit.setText('0')
        self.lineEdit.setAlignment(Qt.AlignmentFlag.AlignCenter)

        self.slider.valueChanged.connect(self.on_opacitySlider_valueChanged)
        self.lineEdit.textChanged.connect(lambda num: self.on_opacityLineEdit_textChanged(num, max))

        self.hBox.addWidget(self.label, 0, Qt.AlignmentFlag.AlignLeft)
        self.hBox.addWidget(self.slider, 0, Qt.AlignmentFlag.AlignLeft)
        self.hBox.addWidget(self.lineEdit, 0, Qt.AlignmentFlag.AlignLeft)

    def setFont(self, font: QFont):
        self._font = font
        self.label.setFont(self.font())
        self.lineEdit.setFont(self.font())
        self.update()

    def setRange(self, min: int, max: int):
        """
        写入范围
        """
        self.slider.setMinimum(min)
        self.slider.setMaximum(max)

    def range(self):
        return self.slider.minimum(), self.slider.maximum()

    def font(self):
        return self._font

    def setText(self, text: str):
        self.label.setText(text)
        self.update()

    def text(self):
        return self.label.text()

    def value(self):
        return self.slider.value()

    def setValue(self, value: int):
        self.slider.setValue(value)

    def on_opacitySlider_valueChanged(self, num: int):
        self.lineEdit.setText(str(num))

    def on_opacityLineEdit_textChanged(self, text: str, max: int):
        if text == '':
            text = 0
        if int(text) > max:
            text = str(max)
            self.lineEdit.setText(text)
        self.slider.setValue(int(text))

    def setValidator(self, validator: QValidator = QIntValidator(0, 100)):
        self.lineEdit.setValidator(validator)

    def validator(self):
        return self.lineEdit.validator()
